/**
 * @author ZhiWen Ren
 * @version 1.0
 * @description: LeetCode-5-最长回文子串
 * @date 2025/8/23 14:31
 */
public class Solution5 {
    public static String longestPalindrome(String s) {
        // 最长回文字串的长度非奇即偶
        String ans = String.valueOf(s.charAt(0));
        int maxLen = 1;

        // 最长回文字串的长度为奇数
        for (int i = 0; i < s.length(); i++) {
            int left = i;
            int right = i;
            while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
                if (right - left + 1 > maxLen) {
                    maxLen = right - left + 1;
                    ans = s.substring(left, right + 1);
                }
                left--;
                right++;
            }
        }

        // 最长回文字串的长度为偶数
        for (int i = 0; i < s.length() - 1; i++) {
            int left = i;
            int right = i + 1;
            while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
                if (right - left + 1 > maxLen) {
                    maxLen = right - left + 1;
                    ans = s.substring(left, right + 1);
                }
                left--;
                right++;
            }

        }
        return ans;
    }

    public static void main(String[] args) {
        longestPalindrome("babad");
    }
}
